package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.DTO.ContractDto;
import com.crm.common.utils.StringUtils;
import com.crm.entity.Activity;
import com.crm.entity.Contract;
import com.crm.entity.Courses;
import com.crm.mapper.ActivityMapper;
import com.crm.mapper.ContractMapper;
import com.crm.mapper.CoursesMapper;
import com.crm.service.ContractService;
import com.crm.vo.ContractVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements ContractService {
    //活动类型 1为课程折扣
    private static final int ACTIVITY_TYPE = 1;
    private static final String  CHANNEL_DISCOUNT_TYPE = "课程折扣";
    private static final String  CHANNEL_MONEY_TYPE = "代金券";


    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CoursesMapper coursesMapper;

    @Autowired
    private ActivityMapper activityMapper;
    /**
     * 查询合同列表
     * @param contractDto
     * @return
     */
    @Override
    public ContractVo listPage(ContractDto contractDto) {
        Page<Contract> page = new Page<>(contractDto.getPageNum(), contractDto.getPageSize());
        LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.hasText(contractDto.getContractNo())){
            wrapper.eq(Contract::getContractNo, contractDto.getContractNo());
        }
        if(StringUtils.hasText(contractDto.getName())){
            wrapper.like(Contract::getName, contractDto.getName());
        }
        if(StringUtils.hasText(contractDto.getPhone())){
            wrapper.eq(Contract::getPhone, contractDto.getPhone());
        }

        Map<String, Object> params = contractDto.getParams();

        String beginCreateTimeStr = (params.get("beginCreateTime") != null) ? params.get("beginCreateTime").toString().trim() : null;
        String endCreateTimeStr = (params.get("endCreateTime") != null) ? params.get("endCreateTime").toString().trim() : null;

        if(StringUtils.hasText(beginCreateTimeStr) && StringUtils.hasText(endCreateTimeStr)){
            wrapper.between(Contract::getCreateTime, beginCreateTimeStr, endCreateTimeStr);
        }

        Page<Contract> contractPage = contractMapper.selectPage(page, wrapper);

        ContractVo contractVo = new ContractVo();

        contractVo.setContracts(contractPage.getRecords());
        contractVo.setPageSize(contractPage.getSize());
        contractVo.setTotalPage(contractPage.getPages());
        contractVo.setTotalCount(contractPage.getTotal());
        return contractVo;
    }

    /**
     * 新增合同
     * @param contractDto
     */
    @Override
    public void saveContract(ContractDto contractDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(contractDto,contract);
        contract.setCreateTime(new Date());
        
        //查课程表，拿到课程价格和课程名称
        LambdaQueryWrapper<Courses> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Courses::getId, contractDto.getCourseId());
        Courses courses = coursesMapper.selectOne(wrapper);
        //赋值课程价格
        BigDecimal price = courses.getPrice();
        contract.setCoursePrice(price);

        //从活动表中获取活动折扣
        Activity activity = activityMapper.selectOne(Wrappers.<Activity>lambdaQuery().eq(Activity::getId, contractDto.getActivityId()));
        //获取活动类型
        Integer type = activity.getType();


        if(type == ACTIVITY_TYPE){
            contract.setDiscountType(CHANNEL_DISCOUNT_TYPE);
            //折扣类型，计算实付金额
            BigDecimal discount = activity.getDiscount();
            contract.setOrder(price.multiply(discount));
        }else {
            contract.setDiscountType(CHANNEL_MONEY_TYPE);
            //代金券
            Integer vouchers = activity.getVouchers();
            if (vouchers != null) {
                // 将Integer转换为BigDecimal，然后使用subtract方法
                BigDecimal voucherAmount = new BigDecimal(vouchers);
                price = price.subtract(voucherAmount);
            } else {
                // 处理vouchers为null的情况，可以记录日志或跳过
                System.out.println("优惠券金额为null");
            }
            contract.setOrder(price);
        }

        //新增合同
        super.save(contract);
        log.info("新增合同成功{}", contract);
    }

    /**
     * 活动详情
     * @param id
     * @return
     */
    @Override
    public Contract getContractById(Long id) {
        
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getId, id));
        return contract;
    }

    /**
     * 修改合同
     * @param contractDto
     * @return
     */
    @Override
    public void updateContract(ContractDto contractDto) {
        //查找合同
        Contract contract = new Contract();
        BeanUtils.copyProperties(contractDto,contract);
        LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Contract::getId,contractDto.getId());
        contractMapper.update(contract,wrapper);

    }
}